<?php

defined('IN_IA') or exit('Access Denied');
define('MUI', '../addons/dayu_sms/mui/');
define('TEMPLATE_WEUI', '../addons/dayu_sms/template/weui/');
class dayu_smsModuleSite extends WeModuleSite
{
	private $sms_table = 'dayu_sms';
	private $table_log = 'dayu_sms_log';
	public function doWebsms()
	{
		global $_W, $_GPC;
		$setting = $this->module['config'];
		$op = trim($_GPC['op']) ? trim($_GPC['op']) : 'list';
		$weid = $_W['uniacid'];
		if ($setting['mode'] == 1) {
			$mode = '阿里大于';
			$appid = '模板ID';
			$templateid = '签名';
		} else {
			$mode = '云之讯';
			$appid = '应用ID';
			$templateid = '短信模板ID';
		}
		if ($op == 'list') {
			$where = ' weid = :weid';
			$params[':weid'] = $weid;
			if (!empty($_GPC['keyword'])) {
				$where .= " AND appid LIKE '%{$_GPC['keyword']}%'";
			}
			$pindex = max(1, intval($_GPC['page']));
			$psize = 20;
			$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->sms_table) . ' WHERE ' . $where, $params);
			$lists = pdo_fetchall('SELECT * FROM ' . tablename($this->sms_table) . ' WHERE ' . $where . ' ORDER BY createtime DESC,id ASC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize, $params, 'id');
			$pager = pagination($total, $pindex, $psize);
			if (checksubmit('submit')) {
				if (!empty($_GPC['ids'])) {
					foreach ($_GPC['ids'] as $k => $v) {
						$data = array('weid' => trim($_GPC['weid'][$k]), 'appid' => trim($_GPC['appid'][$k]), 'templateid' => trim($_GPC['templateid'][$k]), 'title' => trim($_GPC['title'][$k]), 'mode' => intval($_GPC['mode'][$k]));
						pdo_update($this->sms_table, $data, array('weid' => $weid, 'id' => intval($v)));
					}
					message('编辑短信模板成功', $this->createWebUrl('sms', array('op' => 'list', 'weid' => $weid)), 'success');
				}
			}
			include $this->template('sms');
		} elseif ($op == 'post') {
			if (checksubmit('submit')) {
				if (!empty($_GPC['appid'])) {
					foreach ($_GPC['appid'] as $k => $v) {
						$v = trim($v);
						if (empty($v)) {
							continue;
						}
						$data['appid'] = $v;
						$data['appid'] = $_GPC['appid'][$k];
						$data['templateid'] = $_GPC['templateid'][$k];
						$data['weid'] = $_GPC['weid'][$k];
						$data['title'] = $_GPC['title'][$k];
						$data['mode'] = $_GPC['mode'][$k];
						$data['createtime'] = time();
						pdo_insert($this->sms_table, $data);
					}
				}
				message('添加短信模板成功', $this->createWebUrl('sms', array('weid' => $weid, 'op' => 'list')), 'success');
			}
			include $this->template('sms');
		} elseif ($op == 'smsdel') {
			$id = intval($_GPC['id']);
			if (!empty($id)) {
				pdo_delete($this->sms_table, array('id' => $id));
			}
			message('删除成功.', referer());
		}
	}
	public function doWebmoney()
	{
		global $_W, $_GPC;
		$setting = $this->module['config'];
		if ($setting['mode'] == '0') {
			include 'plugin/sms.php';
			$options['accountsid'] = $setting['sms']['accountsid'];
			$options['token'] = $setting['sms']['tokenid'];
			$ucpass = new Ucpaas($options);
			$appId = $setting['sms']['appid'];
			$mobile = "13539220000";
			$clientNumber = '21703';
			$ccc = $ucpass->getClientInfo();
			echo $ccc['respCode'];
		}
		include $this->template('money');
	}
	public function doWebLog()
	{
		global $_W, $_GPC;
		load()->model('mc');
		$modules = uni_modules();
		$weid = $_W['uniacid'];
		$pindex = max(1, intval($_GPC['page']));
		$psize = 20;
		$starttime = empty($_GPC['time']['start']) ? strtotime('-1 month') : strtotime($_GPC['time']['start']);
		$endtime = empty($_GPC['time']['end']) ? TIMESTAMP : strtotime($_GPC['time']['end']) + 86399;
		$where = ' weid = :weid';
		$params[':weid'] = $weid;
		if (!empty($_GPC['keyword'])) {
			$where .= " AND mobile LIKE '%{$_GPC['keyword']}%'";
		}
		if ($_GPC['status'] != '') {
			$where .= " AND status = '{$_GPC['status']}'";
		}
		if ($_GPC['addons'] != '') {
			$where .= " AND addons = '{$_GPC['addons']}'";
		}
		if (!empty($_GPC['time'])) {
			$where .= " AND createtime >= :starttime AND createtime <= :endtime ";
			$params[':starttime'] = $starttime;
			$params[':endtime'] = $endtime;
		}
		$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($this->table_log) . ' WHERE ' . $where, $params);
		$list = pdo_fetchall('SELECT * FROM ' . tablename($this->table_log) . ' WHERE ' . $where . ' ORDER BY createtime DESC,id ASC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize, $params, 'id');
		$pager = pagination($total, $pindex, $psize);
		foreach ($list as &$r) {
			$r['module'] = $modules[$r['addons']];
			$r['user'] = mc_fansinfo($r['openid']);
			$r['sms'] = $this->get_sms($r['sid']);
		}
		include $this->template('log');
	}
	public function doWebAjaxSet()
	{
		global $_GPC, $_W;
		$id = intval($_GPC['id']);
		$type = $_GPC['type'];
		$data = intval($_GPC['data']);
		$table = $_GPC['table'];
		if ($table == 'sms') {
			$table = $this->sms_table;
		}
		if (in_array($type, array('num'))) {
			$data = $data == 1 ? '0' : '1';
			pdo_update($table, array($type => $data), array("id" => $id, "weid" => $_W['uniacid']));
			exit(json_encode(array("result" => 1, "data" => $data)));
		}
		exit(json_encode(array("result" => 0)));
	}
	public function doMobileSendSms()
	{
		global $_W, $_GPC;
		$setting = $this->module['config'];
		$id = intval($_GPC['id']);
		$sql = 'SELECT * FROM ' . tablename($this->sms_table) . ' WHERE `weid`=:weid AND `id`=:id';
		$params = array();
		$params[':weid'] = $_W['uniacid'];
		$params[':id'] = $id;
		$sms = pdo_fetch($sql, $params);
		$to = $_GPC['mobile'];
		if ($sms['mode'] == '0' && $setting['mode'] == 1 || $sms['mode'] == '2') {
			include "plugin/TopSdk.php";
			if ($sms['num'] == 1) {
				$num = random(6, true);
			} else {
				$num = random(4, true);
			}
			$c = new TopClient();
			$c->appkey = $setting['dayu']['appkey'];
			$c->secretKey = $setting['dayu']['appsecret'];
			$req = new AlibabaAliqinFcSmsNumSendRequest();
			$req->setExtend("123456");
			$req->setSmsType("normal");
			$req->setSmsFreeSignName($sms['templateid']);
			$json = json_encode(array("code" => $num, 'ptname' => $sms['templateid']));
			$req->setSmsParam($json);
			$req->setRecNum($to);
			$req->setSmsTemplateCode($sms['appid']);
			$result = $c->execute($req);
			if ($result->result->err_code == '0') {
				$re['state'] = 1;
				$re['yzm'] = $num;
				$re['mobile'] = $to;
				$re['msg'] = '验证码发送成功';
			} else {
				$re['state'] = '0';
				$re['msg'] = $sms['title'] . '发送失败请稍后重试';
			}
		} elseif ($sms['mode'] == '0' && $setting['mode'] == 2 || $sms['mode'] == '3') {
			include "plugin/alisms/Config.php";
			include_once 'plugin/alisms/Request/V20170525/SendSmsRequest.php';
			include_once 'plugin/alisms/Request/V20170525/QuerySendDetailsRequest.php';
			if ($sms['num'] == 1) {
				$num = random(6, true);
			} else {
				$num = random(4, true);
			}
			$accessKeyId = $setting['aliyun']['appkey'];
			$accessKeySecret = $setting['aliyun']['appsecret'];
			$product = "Dysmsapi";
			$domain = "dysmsapi.aliyuncs.com";
			$region = "cn-hangzhou";
			$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
			DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
			$acsClient = new DefaultAcsClient($profile);
			$request = new Dysmsapi\Request\V20170525\SendSmsRequest();
			$request->setPhoneNumbers($to);
			$request->setSignName($sms['appid']);
			$request->setTemplateCode($sms['templateid']);
			$json = json_encode(array("code" => $num, 'ptname' => $sms['templateid']));
			$request->setTemplateParam($json);
			$request->setOutId("1234");
			$acsResponse = $acsClient->getAcsResponse($request);
			$re['state'] = 1;
			$re['yzm'] = $num;
			$re['mobile'] = $to;
			$re['msg'] = '验证码发送成功';
		} elseif ($sms['mode'] == '0' && $setting['mode'] == 5 || $sms['mode'] == '5') {
			include "plugin/alisms/Config.php";
			include_once 'plugin/alisms/Request/V20170525/SendSmsRequest.php';
			include_once 'plugin/alisms/Request/V20170525/QuerySendDetailsRequest.php';
			if ($sms['num'] == 1) {
				$num = random(6, true);
			} else {
				$num = random(4, true);
			}
			$accessKeyId = $setting['aliyun']['appkey'];
			$accessKeySecret = $setting['aliyun']['appsecret'];
			$product = "Dysmsapi";
			$domain = "dysmsapi.aliyuncs.com";
			$region = "cn-hangzhou";
			$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
			DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
			$acsClient = new DefaultAcsClient($profile);
			$request = new Dysmsapi\Request\V20170525\SendSmsRequest();
			$request->setPhoneNumbers($to);
			$request->setSignName($sms['appid']);
			$request->setTemplateCode($sms['templateid']);
			$request->setTemplateParam("{\"code\":\"12345\",\"product\":\"云通信服务\"}");
			$request->setOutId("1234");
			$acsResponse = $acsClient->getAcsResponse($request);
			if ($acsResponse->acsResponse->err_code == 'ok') {
				$re['state'] = 1;
				$re['yzm'] = $num;
				$re['mobile'] = $to;
				$re['msg'] = '验证码发送成功';
			} else {
				$re['state'] = '0';
				$re['msg'] = $sms['title'] . '发送失败请稍后重试';
			}
		} else {
			include 'plugin/sms.php';
			$re['state'] = 0;
			$options['accountsid'] = $setting['ucpaas']['accountsid'];
			$options['token'] = $setting['ucpaas']['tokenid'];
			$ucpass = new Ucpaas($options);
			$appId = $sms['appid'];
			$templateId = $sms['templateid'];
			if ($sms['num'] == 1) {
				$yzm = rand(999999, 100000);
				$num = 0;
			} else {
				$yzm = rand(9999, 1000);
				$num = 0;
			}
			$param = "{$_W['uniaccount']['name']},{$yzm}";
			$iscg = $ucpass->templateSMS($appId, $to, $templateId, $param);
			if ($iscg == $num) {
				if (!empty($options['accountsid']) && !empty($options['token']) && !empty($appId) && !empty($templateId)) {
					$re['state'] = 1;
					$re['yzm'] = $yzm;
					$re['mobile'] = $to;
					$re['msg'] = '验证码发送成功';
				} else {
					$re['msg'] = '发送失败,参数设置错误';
				}
			} else {
				$re['msg'] = '发送失败请稍后重试';
			}
		}
		$log = pdo_fetch("SELECT * FROM " . tablename($this->table_log) . " WHERE weid = :weid AND openid = :openid LIMIT 1", array(':weid' => $_W['uniacid'], ':openid' => $_W['openid']));
		$setting['sendtime'] = !empty($setting['sendtime']) ? $setting['sendtime'] : '1';
		$sendtime = time() - $setting['sendtime'] * 60;
		if (!empty($log['id']) && $log['createtime'] > $sendtime) {
			$sendtime = strtotime("now") - $log['createtime'];
			$re['state'] = '0';
			$re['msg'] = '发送验证码需间隔' . $setting['sendtime'] . '分钟，' . $sendtime . '秒后可发送';
			message($re, '', 'ajax');
			exit;
		} else {
			$data['weid'] = $_W['uniacid'];
			$data['sid'] = $id;
			$data['openid'] = $_GPC['openid'];
			$data['mobile'] = $to;
			$data['addons'] = $_GPC['form'];
			$data['num'] = $re['yzm'];
			$data['mode'] = $setting['mode'];
			$data['status'] = $re['state'];
			$data['createtime'] = TIMESTAMP;
			pdo_insert($this->table_log, $data);
		}
		message($re, '', 'ajax');
	}
	public function sendMobileMSG($uid, $pwd, $mobile, $content)
	{
		$url = 'http://api.sms.cn/sms/?ac=send&uid=' . $uid . '&pwd=' . md5($pwd . $uid) . '&template=100006&mobile=' . $mobile . '&content={code:' . $content . '}';
		$result = file_get_contents($url);
		return $result;
	}
	public function doMobileNotice()
	{
		global $_W, $_GPC;
		$setting = $this->module['config'];
		$id = intval($_GPC['id']);
		$to = $_GPC['mobile'];
		$sql = 'SELECT * FROM ' . tablename($this->sms_table) . ' WHERE `weid`=:weid AND `id`=:id';
		$params = array();
		$params[':weid'] = $_W['uniacid'];
		$params[':id'] = $id;
		$sms = pdo_fetch($sql, $params);
		$result['state'] = 0;
		$options['accountsid'] = $setting['ucpaas']['accountsid'];
		$options['token'] = $setting['ucpaas']['tokenid'];
		$ucpass = new Ucpaas($options);
		$appId = $sms['appid'];
		$templateId = $sms['templateid'];
		$to = $to;
		$member = $_GPC['mname'];
		$mobile = $_GPC['mmobile'];
		$title = $_GPC['content'];
		$param = "{$member},{$mobile},{$title}";
		$iscg = $ucpass->templateSMS($appId, $to, $templateId, $param);
	}
	public function doMobileIndex()
	{
		global $_W, $_GPC;
		if (empty($_W['fans']['uid'])) {
			mc_oauth_userinfo();
		}
		load()->model('mc');
		$weid = $_W['uniacid'];
		$openid = !empty($_W['openid']) ? $_W['openid'] : $_W['fans']['openid'];
		$uid = !empty($_W['member']['uid']) ? $_W['member']['uid'] : $fans['uid'];
		$member = mc_fetch($uid);
		$op = $operation = $_GPC['op'] ? $_GPC['op'] : 'display';
		if ($op == 'post') {
			$update = array('realname' => $_GPC['realname'], 'mobile' => $_GPC['mobile']);
			if (!empty($update)) {
				load()->model('mc');
				if (!$uid) {
					$result['status'] = 0;
					$result['msg'] = '账号异常';
				} elseif (mc_update($uid, $update) === false) {
					$result['status'] = 0;
					$result['msg'] = '没有更改';
				} else {
					$result['status'] = 1;
					$result['msg'] = '保存成功';
				}
				message($result, '', 'ajax');
			}
		}
		$id = intval($_GPC['id']);
		$sms = pdo_get($this->sms_table, array('id' => $id, 'weid' => $weid), array());
		if (!$id || !$sms) {
			message('非法进入');
		}
		include $this->template('index');
	}
	public function doMobileCheckMobile()
	{
		global $_W, $_GPC;
		$log = pdo_get('dayu_sms_log', array('weid' => $_W['uniacid'], 'mobile' => $_GPC['mobile'], 'openid' => $_GPC['openid'], 'status' => 1), array('id'));
		if (!empty($log['id'])) {
			$result['status'] = 1;
			$result['mobile'] = $_GPC['mobile'];
			$result['msg'] = '存在记录';
			message($result, '', 'ajax');
		} else {
			$result['status'] = 0;
			$result['yzm'] = $_GPC['sms'];
			$result['msg'] = '不存在记录';
			message($result, '', 'ajax');
		}
	}
	public function get_sms($id)
	{
		global $_GPC, $_W;
		return pdo_get($this->sms_table, array('weid' => $_W['uniacid'], 'id' => $id), array());
	}
}